def solve(intervals, newIntervals):
    intervals.append(newIntervals)
    intervals.sort(key=lambda x: -x[1])
    temp = []
    ls = intervals[0]
    for i in range(1, len(intervals)):
        left, right = intervals[i]
        if right < ls[0]:
            temp.append(ls)
            ls = [left, right]
        elif right >= ls[0] and left < ls[0]:
            ls = [left, ls[1]]

    temp.append(ls)
    temp.sort(key=lambda x: x[0])
    return temp


if __name__ == "__main__":
    intervals = [[1, 2], [3, 5], [6, 7], [8, 10], [12, 16]]
    newInterval = [4, 8]
    print(solve(intervals, newInterval))
